import serial
import time
import os
import sys
import random
import re

# 定义常量
A_DEBUG_PORT = "COM4"
A_AT_PORT = "COM42"
BAUDRATE = 115200

# 定义变量
at_serial = None
A_debug_serial = None

# 记录运行次数
runTimes = 0

# log文件
AT_LOG = ""
ModulA_DEBUG_LOG = ""

# 日志写入函数
def write_log(log, logFile=""):
    try:
        with open(logFile, 'a') as file_object:
            file_object.write(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "\r\n" + log + "\r\n")
        print(log)
    except PermissionError as e:
        print(f"日志写入失败，权限问题: {e}")
    except Exception as e:
        print(f"日志写入失败，未知错误: {e}")

# 发送AT指令
def at_write(command, timeout, at_port_opened, at_result, RDY=0, CPIN=0):
    at_command = command.encode("UTF-8")
    at_port_opened.write(at_command)

# 读取AT口返回
def at_read(serial_port, logFile=""):
    rec_str = ''
    while True:
        time.sleep(1)
        lenth = serial_port.inWaiting()
        if lenth > 0:
            rec_str = serial_port.read(size=lenth)
            try:
                rec_str = re.sub('\\x1b.*?m', "", rec_str.decode("UTF-8"), 0, re.I)
                if logFile != "":
                    with open(logFile, 'a') as file_object:
                        rec_str = str(time.time()) + ":" + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "\r\n" + rec_str
                        file_object.write(str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "\r\n" + rec_str + "\r\n")
                return rec_str
            except:
                return ""
        else:
            break
    return rec_str

# 检查端口连接状态
def check_port_status(COM_PORT):
    try:
        debug_serial = serial.Serial(COM_PORT, BAUDRATE)
        print(f"成功连接到 {COM_PORT}")
        return debug_serial
    except serial.SerialException as e:
        print(f"无法连接到端口 {COM_PORT}，请检查设备连接: {e}")
        sys.exit()
    except Exception as e:
        print(f"连接到端口 {COM_PORT} 时发生未知错误: {e}")
        sys.exit()

# 检查AT口通信状态
def check_AT_singnal():
    global at_serial
    if at_serial is None:
        try:
            at_serial = serial.Serial(A_AT_PORT, BAUDRATE)
        except:
            print("AT口连接失败，请检查端口")
            sys.exit()

# debug口登录模块
def loginDevice(debug_serial, debug_log):
    while True:
        print("等待登录... ... ")
        time.sleep(3)
        at_write("\r\n", 3, debug_serial, "OK")
        result = at_read(debug_serial, debug_log)
        if "login:" in result:
            at_write("root\r\n", 3, debug_serial, "OK")
            write_log("账号输入成功", debug_log)
            time.sleep(2)
            at_write("oelinux123\r\n", 3, debug_serial, "OK")
            write_log("密码输入成功", debug_log)
            at_read(debug_serial, debug_log)
            at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            at_read(debug_serial, debug_log)
        elif "~ #" in result or '/ #' in result:
            write_log("登录成功", debug_log)
            at_write("echo 2 >/proc/sys/kernel/printk\r\n", 3, debug_serial, "OK")
            at_read(debug_serial, debug_log)
            break
        else:
            write_log("登录失败，重新尝试", debug_log)
            time.sleep(3)

def createLogFile():
    global AT_LOG
    global ModulA_DEBUG_LOG
    AT_LOG = "AT_LOG_{}.log".format(time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()))
    ModulA_DEBUG_LOG = "ModulA_DEBUG_LOG_{}.log".format(time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime()))

def writeRuntimesToLog():
    global runTimes
    with open(ModulA_DEBUG_LOG, 'a+') as file_object:
        file_object.write("\r\n{} runtimes: {} {}\r\n".format("<"*20, runTimes, ">"*20))
    with open(AT_LOG, 'a+') as file_object:
        file_object.write("\r\n{} runtimes: {} {}\r\n".format("<"*20, runTimes, ">"*20))
    runTimes += 1
    print("运行次数: ", runTimes)
def modem_reset():
    at_write("cd /data\r\n", 3, A_debug_serial, "OK")
    at_write("./test_sdk_api\r\n", 3, A_debug_serial, "OK")
    time.sleep(1)
    at_write("7\r\n", 3, A_debug_serial, "OK")
    at_read(A_debug_serial, ModulA_DEBUG_LOG)
    time.sleep(1)
    at_write("0\r\n", 3, A_debug_serial, "OK")
    at_read(A_debug_serial, ModulA_DEBUG_LOG)
    time.sleep(1)
    at_write("6\r", 3, A_debug_serial, "OK")  # 设置重启modem cb
    at_read(A_debug_serial, ModulA_DEBUG_LOG)
    time.sleep(1)
    at_write("1\r", 3, A_debug_serial, "OK")
    at_read(A_debug_serial, ModulA_DEBUG_LOG)
    time.sleep(1)
    at_write("29\r", 25, A_debug_serial, "OK")  # 重启modem
    write_log("开始重启modem", ModulA_DEBUG_LOG)
    time.sleep(10)
    result = at_read(A_debug_serial, ModulA_DEBUG_LOG)
    # print(result)
    if "OFFLINE" in result and "ONLINE" in result:
        write_log("modem重启成功", ModulA_DEBUG_LOG)
    else:
        write_log("modem重启失败", ModulA_DEBUG_LOG)
        sys.exit()
    time.sleep(10)
# 清理资源
def cleanup():
    global at_serial, A_debug_serial
    if at_serial:
        at_serial.close()
    if A_debug_serial:
        A_debug_serial.close()
    print("所有资源已释放")

if __name__ == "__main__":
    try:
        # 连接端口
        A_debug_serial = check_port_status(A_DEBUG_PORT)
        createLogFile()
        loginDevice(A_debug_serial, ModulA_DEBUG_LOG)
        while True:
            write_log("**********开始测试**********", ModulA_DEBUG_LOG)
            writeRuntimesToLog()
            modem_reset()
            time.sleep(30)
    except KeyboardInterrupt:
        print("程序被用户中断")
    finally:
        cleanup()
